package org.davidliebman.android.flyer;


import java.lang.reflect.Field;
import java.util.ArrayList;


import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Pager extends SherlockFragmentActivity {
	

    private static final int NUM_PAGES = 3;

    private static final int HOWTO = 0;
    private static final int PLAYERS = 1;
    private static final int HIGHSCORES = 2;
    
    private ViewPager mPager;
    private PagerAdapter mPagerAdapter;

    public static final String AWESOME_NAME = new String("org.awesomeflyer");
    public static final String SAVED_RECORD_ID = new String("saved_record_id");
    public static final String SAVED_NUM_SCORES = new String("saved_num_scores");
    
	public static final String SAVED_ROOM_NUM = new String("room");
	public static final String SAVED_LOOK_FOR_XML = new String("look_for_xml");
	public static final String SAVED_REMEMBER_PLAYER = new String("remember_player");
	public static final String SAVED_ANALYTICS = new String("analytics_tracking");
	public static final String SAVED_TOS = new String("terms_of_service_shown");
	public static final String SAVED_VERSIONCODE = new String("old_versioncode");
    public static final String SAVED_SCREEN_ORIENTATION = new String("screen_orientation");
    public static final String SAVED_FRAGMENT_NUM = new String("fragment_num");

    private SharedPreferences mPreferences;
    
    public static final int MENU_BASE = Menu.FIRST;
    public static final int MENU_GROUP_SUBMENU = MENU_BASE + 1;
    public static final int MENU_GROUP_ROOMS = MENU_BASE + 2; //this is always last entry


    //private RecordAdapter mAdapter;
    public static final int DIALOG_PREFERENCES = 0;
    public static final int DIALOG_WEB_SUCCESS = 1;
    public static final int DIALOG_WEB_FAILURE = 2;
    public static final int DIALOG_USERNUM_CHANGED = 3;
    public static final int DIALOG_STARTGAME = 4;
    public static final int DIALOG_UNUSED = 5;
    
    public static final int SCREEN_LANDSCAPE = 0;
    public static final int SCREEN_PORTRAIT = 1;

    private int mScreenOrientation = Pager.SCREEN_PORTRAIT;
    private int mRoomNumSelected = 1;
    private boolean mLookForXml;
    private boolean mIsNewRecord = false;
    private boolean mShowMenu = true;
    
    protected boolean mActive = true;
    private boolean mRememberPlayer = true;
    private boolean mGoogleAnalytics;
    private boolean mTermsOfService;
    private int mVersionCode = 1;
    public static final String UA_NUMBER = new String("UA-19479622-6");
    public GoogleAnalyticsTracker tracker;
    private Record mHighScores;
    private Scores.ScoreOpenHelper mScoresHelper;
    private Scores mScores;
    private SQLiteDatabase db;
    
	private InitBackground.LevelList mList;
	private InitBackground.ParseXML mParser = new InitBackground.ParseXML(this);
	private ParseChallengeXML mChallengeParser = new ParseChallengeXML(this);

    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pager);

      
        // Instantiate a ViewPager and a PagerAdapter.
        mPager = (ViewPager) findViewById(R.id.pager);
        mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
        mPager.setAdapter(mPagerAdapter);
         
        // always show menu key even with hardware key...
        try {
            ViewConfiguration config = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
            if(menuKeyField != null) {
                menuKeyField.setAccessible(true);
                menuKeyField.setBoolean(config, false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        // google analytics tracker...
        mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        mGoogleAnalytics = mPreferences.getBoolean(Pager.SAVED_ANALYTICS, true);

        
        
        tracker = GoogleAnalyticsTracker.getInstance();
        tracker.start(UA_NUMBER, 5, this);
        if (mGoogleAnalytics) {
            tracker.trackPageView("/SplashScreen");
            tracker.dispatch();
            //Log.e("awesomeflyer","Google Analytics-----------------");
        }
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflate = this.getSupportMenuInflater();//getMenuInflater();
    	inflate.inflate(R.menu.main_menu, menu);
    	

    	return true;
    	
    }
    
    
    
    @Override
    public void onResume() {
    	super.onResume();
    	
    	//this.showView(VIEW_PLAYERS);
        mScores = new Scores(Pager.this.getApplicationContext(), mHighScores);

    	/* retrieve Record mHighScores */
    	mHighScores = new Record();
        //mPreferences = PreferenceManager.getDefaultSharedPreferences(this);//getSharedPreferences(AWESOME_NAME, MODE_PRIVATE);
        
        //mRememberPlayer = mPreferences.getBoolean(Pager.SAVED_REMEMBER_PLAYER, true);
        //mHighScores = new Record();

//        if(!mRememberPlayer) {
//        	//mHighScores.addToPreferences(mPreferences);
//        	Log.e("pager", "save new");
//        	
//        }
//        else {
        	//mHighScores.getFromPreferences(mPreferences);
        	mHighScores = mScores.getHighScorePrefs();
        	Log.e("pager", "load");
//        }
        
  

        //mScores = new Scores(Pager.this, mHighScores);


    	
    	/////////////////////////////start TOS
        mPreferences = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());//getSharedPreferences(AWESOME_NAME, MODE_PRIVATE);

        mLookForXml = mPreferences.getBoolean(SAVED_LOOK_FOR_XML, false);
        //mRememberPlayer = mPreferences.getBoolean(SAVED_REMEMBER_PLAYER, true);
        
    	 /* get TOS info from preferences */
        mGoogleAnalytics = mPreferences.getBoolean(Pager.SAVED_ANALYTICS, true);
        mTermsOfService = mPreferences.getBoolean(Pager.SAVED_TOS, false);
        //Log.e("tag", "version code saved " + mPreferences.getInt(SAVED_VERSIONCODE, 1));
        
        /* check version / show TermsOfService.java */
        PackageManager mManager = getPackageManager();
        try {
        	PackageInfo mInfo = mManager.getPackageInfo("org.davidliebman.android.flyer", 0);
        	mVersionCode = mInfo.versionCode;
        	
        }
        catch (NameNotFoundException e) {
        	// not a big deal if Package Manager 
        	// doesn't find the version code.
        	e.printStackTrace();
        	mVersionCode = 1;
        }
        /* if game was just updated, show TOS page. */
        if (mPreferences.getInt(Pager.SAVED_VERSIONCODE, 1) != mVersionCode) {
        	mTermsOfService = false;
        	this.mPager.setCurrentItem(HOWTO);
        }
        
        /* reset preferences so that game starts with room 1 */
        SharedPreferences.Editor e = mPreferences.edit();
        e.putInt(Options.SAVED_ROOM_NUM, 1);
        e.commit();
        
       
    	////////////////////////////start splashscreen
        
//    	mSplash = new SplashScreen();
//    	mSplash.execute(new Integer[] {0});
    	
    }
    
    @Override
	public void onDestroy() {
    	super.onDestroy();
    	
    	try {
    		tracker.stop();
    	}
    	catch (Exception e) {
    		e.printStackTrace();
    	}
    }
    
    @Override
    public void onPause() {
    

        mPreferences = PreferenceManager.getDefaultSharedPreferences(this);//getSharedPreferences(AWESOME_NAME, MODE_PRIVATE);
    	//mHighScores.addToPreferences(mPreferences);
    	//mScores.insertPrefs(mHighScores);
    	SharedPreferences.Editor edit = mPreferences.edit();
        edit.putBoolean(SAVED_REMEMBER_PLAYER, mRememberPlayer);
        edit.commit();
    	try {
    		mScores.closeAll();
    	}
    	catch(NullPointerException e) {
    		//Log.e("Awesomeguy", "Null Pointer Players");
    	}
    	finish();
    	super.onPause();
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
    	
        mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        this.mScreenOrientation = mPreferences.getInt(Pager.SAVED_SCREEN_ORIENTATION, Pager.SCREEN_PORTRAIT);
        mScores = new Scores(Pager.this.getApplicationContext(), mHighScores);

        //mHighScores.getFromPreferences(mPreferences);
    	mHighScores = mScores.getHighScorePrefs();
    	mList = new InitBackground.LevelList();
    	mList = mChallengeParser.getLevelList(mLookForXml);
    	
    	//erase old room menu
    	menu.removeGroup(Pager.MENU_GROUP_SUBMENU);
    	//must populate menu entries for level
    	SubMenu mRoomMenu = menu.addSubMenu(Pager.MENU_GROUP_SUBMENU, 0, 1, "Starting Level");
    	for (int x = 0; x < mList.size(); x ++ ) {
    		mRoomMenu.add(Pager.MENU_GROUP_ROOMS,Pager.MENU_BASE + mList.getNum(x), 0, "Level #" + mList.getNum(x));	
    	}
    	mRoomMenu.setGroupCheckable(Pager.MENU_GROUP_ROOMS, true, true);

    	//set one entry as selected
    	for (int x = 0; x < mList.size(); x ++ ) {
    		if (this.mRoomNumSelected == mList.getNum(x)) {
    			menu.findItem(Pager.MENU_BASE + mList.getNum(x)).setChecked(true);
    		}
    	}
    	
    	//set game speed
    	if (mHighScores.getGameSpeed() == Record.SPEED_SLOW_16) {
    		menu.findItem(R.id.menu_options_speed_slow_item).setChecked(true);
    	}
    	if (mHighScores.getGameSpeed() == Record.SPEED_MEDIUM_20) {
    		menu.findItem(R.id.menu_options_speed_medium_item).setChecked(true);
    	}
    	if (mHighScores.getGameSpeed() == Record.SPEED_FAST_24) {
    		menu.findItem(R.id.menu_options_speed_fast_item).setChecked(true);
    	}
    	if (mHighScores.getGameSpeed() == Record.SPEED_FASTER_32) {
    		menu.findItem(R.id.menu_options_speed_faster_item).setChecked(true);
    	}
    	
    	if (mHighScores.getGameSpeed() == Record.SPEED_SYSTEM_40) {
    		menu.findItem(R.id.menu_options_speed_system_item).setChecked(true);
    	}
    	//play game sound
    	if (!mHighScores.isSound()) {
    		menu.findItem(R.id.menu_options_sound_no_item).setChecked(true);
    	}
    	else {
    		menu.findItem(R.id.menu_options_sound_yes_item).setChecked(true);
    	}
    	//how many players
    	if (mHighScores.getNumRecords() == Record.RADIO_PLAYERS_FIFTY) {
    		menu.findItem(R.id.menu_options_players_fifty_item).setChecked(true);
    	}
    	if (mHighScores.getNumRecords() == Record.RADIO_PLAYERS_TEN) {
    		menu.findItem(R.id.menu_options_players_ten_item).setChecked(true);
    	}
    	if (mHighScores.getNumRecords() == Record.RADIO_PLAYERS_FIVE) {
    		menu.findItem(R.id.menu_options_players_five_item).setChecked(true);
    	}
    	//remember me
    	if (mRememberPlayer) {
    		menu.findItem(R.id.menu_options_rememberme_yes_item).setChecked(true);
    	}
    	else {
    		menu.findItem(R.id.menu_options_rememberme_no_item).setChecked(true);
    	}
    	//look for xml
    	if (!mLookForXml) {
    		menu.findItem(R.id.menu_options_xml_no_item).setChecked(true);
    	}
    	else {
    		menu.findItem(R.id.menu_options_xml_yes_item).setChecked(true);
    	}
    	//use google analytics
    	if (mGoogleAnalytics ) {
    		menu.findItem(R.id.menu_options_analytics_yes_item).setChecked(true);
    	}
    	else {
    		menu.findItem(R.id.menu_options_analytics_no_item).setChecked(true);
    	}
    	//will game have monsters?
    	if (mHighScores.isEnableMonsters()) {
    		menu.findItem(R.id.menu_options_monsters_yes_item).setChecked(true);
    	}
    	else {
    		menu.findItem(R.id.menu_options_monsters_no_item).setChecked(true);
    	}
    	//will game have collision?
    	if (mHighScores.isEnableCollision()) {
    		menu.findItem(R.id.menu_options_collision_yes_item).setChecked(true);
    	}
    	else {
    		menu.findItem(R.id.menu_options_collision_no_item).setChecked(true);
    	}
    	
    	if (this.mScreenOrientation == Pager.SCREEN_PORTRAIT) {
    		menu.findItem(R.id.menu_options_orientation_portrait_item).setChecked(true);
    	}
    	else if (this.mScreenOrientation == Pager.SCREEN_LANDSCAPE) {
    		menu.findItem(R.id.menu_options_orientation_landscape_item).setChecked(true);
    	}
    	
    	return this.mShowMenu;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	boolean mTest = false;
    	
    	if (item.getItemId() == R.id.menu_game_item) {
    		
    		mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
            this.mScreenOrientation = mPreferences.getInt(Pager.SAVED_SCREEN_ORIENTATION, Pager.SCREEN_PORTRAIT);
			Intent StartGameIntent = new Intent(Pager.this,GameStart.class);
            
            
    		if (this.mScreenOrientation == Pager.SCREEN_PORTRAIT) StartGameIntent = new Intent(Pager.this, GameStartPort.class);
    		if (this.mScreenOrientation == Pager.SCREEN_LANDSCAPE) StartGameIntent = new Intent(Pager.this, GameStartLand.class);
    		
        	
			startActivity(StartGameIntent);
		} else if (item.getItemId() == R.id.menu_options_speed_slow_item) {
			if (!item.isChecked()) {
    			item.setChecked(true);
    			mHighScores.setGameSpeed(Record.SPEED_SLOW_16);
    			mTest = true;
    		}
		} else if (item.getItemId() == R.id.menu_options_speed_medium_item) {
			if (!item.isChecked()) {
    			item.setChecked(true);
    			mHighScores.setGameSpeed(Record.SPEED_MEDIUM_20);
    			mTest = true;
    		}
		} else if (item.getItemId() == R.id.menu_options_speed_fast_item) {
			if (!item.isChecked()) {
    			item.setChecked(true);
    			mHighScores.setGameSpeed(Record.SPEED_FAST_24);
    			mTest = true;
    		}
		} else if (item.getItemId() == R.id.menu_options_speed_faster_item) {
			if (!item.isChecked()) {
    			item.setChecked(true);
    			mHighScores.setGameSpeed(Record.SPEED_FASTER_32);
    			mTest = true;
    		}
		} else if (item.getItemId() == R.id.menu_options_speed_system_item) {
			if (!item.isChecked()) {
    			item.setChecked(true);
    			mHighScores.setGameSpeed(Record.SPEED_SYSTEM_40);
    			mTest = true;
    		}
		} else if (item.getItemId() == R.id.menu_options_players_fifty_item) {
			if (!item.isChecked()) {
    			item.setChecked(true);
    			mHighScores.setNumRecords(Record.RADIO_PLAYERS_FIFTY);
    			//showDialog(Players.DIALOG_USERNUM_CHANGED);
    			mTest = true;
    		}
		} else if (item.getItemId() == R.id.menu_options_players_ten_item) {
			if (!item.isChecked()) {
    			item.setChecked(true);
    			mHighScores.setNumRecords(Record.RADIO_PLAYERS_TEN);
    			//showDialog(Players.DIALOG_USERNUM_CHANGED);
    			mTest = true;
    		}
		} else if (item.getItemId() == R.id.menu_options_players_five_item) {
			if (!item.isChecked()) {
    			item.setChecked(true);
    			mHighScores.setNumRecords(Record.RADIO_PLAYERS_FIVE);
    			//showDialog(Players.DIALOG_USERNUM_CHANGED);
    			mTest = true;

    		}
		} else if (item.getItemId() == R.id.menu_options_sound_yes_item) {
			if (!item.isChecked()) {
    			item.setChecked(true);
    			mHighScores.setSound(true);
    			mTest = true;

    		}
		} else if (item.getItemId() == R.id.menu_options_sound_no_item) {
			if (!item.isChecked()) {
    			item.setChecked(true);
    			mHighScores.setSound(false);
    			mTest = true;

    		}
		} else if (item.getItemId() == R.id.menu_options_rememberme_yes_item) {
			if (!item.isChecked()) {
    			item.setChecked(true);
    			this.mRememberPlayer = true;
    			mTest = true;

    		}
		} else if (item.getItemId() == R.id.menu_options_rememberme_no_item) {
			if (!item.isChecked()) {
    			item.setChecked(true);
    			this.mRememberPlayer = false;
    			mTest = true;

    		}
		} else if (item.getItemId() == R.id.menu_options_xml_yes_item) {
			if (!item.isChecked()) {
    			item.setChecked(true);
    			this.mLookForXml = true;
    			mTest = true;

    		}
		} else if (item.getItemId() == R.id.menu_options_xml_no_item) {
			if (!item.isChecked()) {
    			item.setChecked(true);
    			this.mLookForXml = false;
    			mTest = true;

    		}
		} else if (item.getItemId() == R.id.menu_options_analytics_yes_item) {
			if (!item.isChecked()) {
    			item.setChecked(true);
    			this.mGoogleAnalytics = true;
    			mTest = true;

    		}
		} else if (item.getItemId() == R.id.menu_options_analytics_no_item) {
			if (!item.isChecked()) {
    			item.setChecked(true);
    			this.mGoogleAnalytics = false;
    			mTest = true;

    		}
		} else if (item.getItemId() == R.id.menu_options_monsters_yes_item) {
			if (!item.isChecked()) {
    			item.setChecked(true);
    			mHighScores.setEnableMonsters(true);
    			mTest = true;

    		}
		} else if (item.getItemId() == R.id.menu_options_monsters_no_item) {
			if (!item.isChecked()) {
    			item.setChecked(true);
    			this.mHighScores.setEnableMonsters(false);
    			mTest = true;

    		}
		} else if (item.getItemId() == R.id.menu_options_collision_yes_item) {
			if (!item.isChecked()) {
    			item.setChecked(true);
    			this.mHighScores.setEnableCollision(true);
    			mTest = true;

    		}
		} else if (item.getItemId() == R.id.menu_options_collision_no_item) {
			if (!item.isChecked()) {
    			item.setChecked(true);
    			this.mHighScores.setEnableCollision(false);
    			mTest = true;

    		}
		} else if (item.getItemId() == R.id.menu_options_orientation_landscape_item) {
			if (!item.isChecked()) {
    			item.setChecked(true);
    			this.mScreenOrientation = Pager.SCREEN_LANDSCAPE;
    			mTest = true;
    		}
		} else if (item.getItemId() == R.id.menu_options_orientation_portrait_item) {
			if (!item.isChecked()) {
    			item.setChecked(true);
    			this.mScreenOrientation = Pager.SCREEN_PORTRAIT;
    			mTest = true;
    		}
		} else if (item.getItemId() == R.id.menu_url_item) {
			try {
	    		ActivityManager actMngr = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
	    		String runningPkg = actMngr.getRunningTasks(1).get(0).topActivity.getPackageName();
	
	    		PackageManager pm = getPackageManager();
	    		ApplicationInfo ai = pm.getApplicationInfo(runningPkg , 0);
	    		
	    		String url = WebScoreUpload.MY_URL + WebScoreUpload.MY_PATH_INDEX + "?game=" +
	    				ai.packageName;
	    		
	    		//Log.e("Players ----","package: " +ai.packageName);
	    		
	    		Intent i = new Intent(Intent.ACTION_VIEW);
	    		i.setData(Uri.parse(url));
	    		startActivity(i);
    		}
    		catch (Exception e ) {
    			e.printStackTrace();
    		}
		} else if (item.getItemId() == R.id.menu_username_item) {
			Intent intent = new Intent(Pager.this, WebAuthActivity.class);
			intent.putExtra(WebAuth.EXTRA_NAME, WebAuth.TASK_USERNAME);
			startActivity(intent);
		}
    	
    	for (int x = 0; x < mList.size(); x ++ ) {
    		if (Pager.MENU_BASE + mList.getNum(x) == item.getItemId()) {
    			this.mRoomNumSelected = x + 1;
    		}
    	}
    
    	if (mTest) {
	    	mPreferences = PreferenceManager.getDefaultSharedPreferences(this);//this.getSharedPreferences(AWESOME_NAME, MODE_PRIVATE);
	    	SharedPreferences.Editor edit = mPreferences.edit();
	    	
	        edit.putInt(SAVED_ROOM_NUM, mRoomNumSelected);
	        edit.putBoolean(SAVED_LOOK_FOR_XML, mLookForXml);
	        edit.putBoolean(SAVED_REMEMBER_PLAYER, mRememberPlayer);
	        edit.putBoolean(SAVED_ANALYTICS, mGoogleAnalytics);
	        edit.putInt(Pager.SAVED_SCREEN_ORIENTATION, this.mScreenOrientation);
	        //edit.apply();
	        edit.commit();
	    	     
	        
	        Log.e("pager", "menu");
	        
	        //mHighScores.listInLog();
	        
	    	//mPreferences = PreferenceManager.getDefaultSharedPreferences(this);//this.getSharedPreferences(AWESOME_NAME, MODE_PRIVATE);
	    	//mHighScores.addToPreferences(mPreferences);
	    	mScores.insertPrefs(mHighScores);
	    	mScores.setHighScores(mHighScores);
	    	mScores.updateOptions(mHighScores.getRecordIdNum());
    	}
    	return true;
    }
    
    protected Dialog onCreateDialog(int mId) {
    	Dialog  dialog = new Dialog(this);
    	AlertDialog.Builder builder;
    	AlertDialog alertDialog;
    	LayoutInflater mInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    	View mLayout;
    	
    	mLayout = mInflater.inflate(R.layout.congrats, 
    			(ViewGroup) findViewById(R.id.layout_root));
    	mLayout.findViewById(R.id.image).setBackgroundResource(R.drawable.ic_launcher);
    	
    	switch (mId) {
    	/////////////////////////////////////
    	case Pager.DIALOG_USERNUM_CHANGED:
    		//old: mPreferredNumRecords
    		//new: mHighScores.getNumRecords()
 		   if ( mHighScores.getNumRecords() != mHighScores.getNumRecords() ) {
	   	    	builder = new AlertDialog.Builder(Pager.this);
	   	    	builder.setView(mLayout);
	   	    	String mAMessage = new String("Your old preference for 'Number of Player Records' is " 
	   	    			+ mHighScores.getNumRecords());
	   	    	((TextView)mLayout.findViewById(R.id.congrats_text)).setText(mAMessage);
	   	    	String mPositive = new String("Choose " + mHighScores.getNumRecords() + " records.");
	   	    	String mNegative = new String("Choose " + mHighScores.getNumRecords() + " records.");
	   	    	builder.setCancelable(false)
	   	    	       .setPositiveButton(mPositive, new DialogInterface.OnClickListener() {
	   	    	           public void onClick(DialogInterface dialog, int id) {
	   	    	        	   //adjustPlayersList(mHighScores.getNumRecords());
	   	    	        	   dialog.cancel();
	   	    	        	   removeDialog(Pager.DIALOG_USERNUM_CHANGED);
	   	    	           }
	   	    	       })
	   	    	       .setNegativeButton(mNegative, new DialogInterface.OnClickListener() {
	   	    	           public void onClick(DialogInterface dialog, int id) {
	   	    	        	   mHighScores.setNumRecords(mHighScores.getNumRecords());	
	   	    	        	   removeDialog(Pager.DIALOG_USERNUM_CHANGED);
	   	    	                dialog.cancel();
	   	    	           }
	   	    	       });
	   	    	AlertDialog alert = builder.create();
	   	    	dialog = (Dialog) alert;
	       	}
    		
    		break;
    	////////////////////////////////////
    	case Pager.DIALOG_STARTGAME:
    		
    		builder = new AlertDialog.Builder(Pager.this);
    		builder.setView(mLayout);
   	    	String mAMessage = new String("Play Awesome Flyer as \'" + mHighScores.getName() +
   	    			"\' or choose another player:");
   	    	((TextView)mLayout.findViewById(R.id.congrats_text)).setText(mAMessage);

   	    	String mPositive = new String("Choose " + mHighScores.getName() );
   	    	String mNegative = new String("Stay on this screen." );
   	    	builder.setCancelable(false)
   	    	       .setPositiveButton(mPositive, new DialogInterface.OnClickListener() {
   	    	    	   public void onClick(DialogInterface dialog, int id) {
   	    	    		   mPreferences = getSharedPreferences(AWESOME_NAME, MODE_PRIVATE);
   	    	    		   
   	    	    		   mScores.insertPrefs(mHighScores);
   	    	    		   
   	    	    		   Intent StartGameIntent = new Intent(Pager.this,GameStart.class);
   	    	    		   startActivity(StartGameIntent);   	    	        	   
   	    	    		   dialog.cancel();
   	    	        	   removeDialog(Pager.DIALOG_STARTGAME);
   	    	           }
   	    	       })
   	    	       .setNegativeButton(mNegative, new DialogInterface.OnClickListener() {
   	    	           public void onClick(DialogInterface dialog, int id) {
   	    	        	   	removeDialog(Pager.DIALOG_STARTGAME);
   	    	                dialog.cancel();
   	    	           }
   	    	       });
   	    	AlertDialog alert = builder.create();
   	    	dialog = (Dialog) alert;
    		
    		break;
    	////////////////////////////////////
    	case Pager.DIALOG_UNUSED:
    		break;
    	////////////////////////////////////
    		
    	case Pager.DIALOG_PREFERENCES:
    		/*
    		builder = new AlertDialog.Builder(this);
    		builder.setView(mLayout);

    		String mPart = new Integer(mRec.getGameSpeed()).toString();
    		if (mRec.getGameSpeed() >= Record.SPEED_SYSTEM_40) mPart = "System Defined";


    		mAMessage = new String("Score: " + mRec.getHigh() +"*\n" + 
    				"This player uses the handle \'" + mRec.getName() +
    				"\'. They got this score with these special settings:" +
    				"\nGame Speed: " +
    				mPart +
    				"\nGame Sound: " +
    				new Boolean(mRec.isSoundOn()).toString() +
    				"\nEnable Monsters: " +
    				new Boolean(mRec.isEnableMonsters()).toString()) ;
    		if(mRec.isEnableMonsters()) {
    			mAMessage = mAMessage + "\nMonster Collision: " +
    					new Boolean(mRec.isMonsterCollision()).toString();
    		}
    		mAMessage = mAMessage + "\nAlso: " +
    				"\nLives: " + mRec.getLives() ;
    		((TextView)mLayout.findViewById(R.id.congrats_text)).setText(mAMessage);

    		mPositive = new String("OK"  );
    		//String mNegative = new String("Stay on this screen." );
    		builder.setCancelable(false)
    		.setPositiveButton(mPositive, new DialogInterface.OnClickListener() {
    			public void onClick(DialogInterface dialog, int id) {
    				//mPreferences = getSharedPreferences(AWESOME_NAME, MODE_PRIVATE);
    				removeDialog(Pager.DIALOG_PREFERENCES);
    				dialog.cancel();
    				//removeDialog(Highscores.DIALOG_PREFERENCES);
    			}
    		});
    		alert = builder.create();
    		dialog = (Dialog) alert;
			*/
    		break;
    		////////////////////////////////////
    	case Pager.DIALOG_WEB_FAILURE:
    		builder = new AlertDialog.Builder(this);
    		builder.setView(mLayout);

    		mAMessage = new String("Connection to the internet failed, or the server is down. Try again later.") ;

    		((TextView)mLayout.findViewById(R.id.congrats_text)).setText(mAMessage);

    		mPositive = new String("OK"  );
    		//String mNegative = new String("Stay on this screen." );
    		builder.setCancelable(false)
    		.setPositiveButton(mPositive, new DialogInterface.OnClickListener() {
    			public void onClick(DialogInterface dialog, int id) {
    				//mPreferences = getSharedPreferences(AWESOME_NAME, MODE_PRIVATE);
    				removeDialog(Pager.DIALOG_WEB_FAILURE);
    				dialog.cancel();
    				//removeDialog(Highscores.DIALOG_PREFERENCES);
    			}
    		});
    		alert = builder.create();
    		dialog = (Dialog) alert;
    		break;

    	case Pager.DIALOG_WEB_SUCCESS:
    		builder = new AlertDialog.Builder(this);
    		builder.setView(mLayout);

    		mAMessage = new String("Your score has been submitted to the online database. " +
    				"You will not be able to submit any score twice.") ;


    		((TextView)mLayout.findViewById(R.id.congrats_text)).setText(mAMessage);

    		mPositive = new String("OK"  );
    		//String mNegative = new String("Stay on this screen." );
    		builder.setCancelable(false)
    		.setPositiveButton(mPositive, new DialogInterface.OnClickListener() {
    			public void onClick(DialogInterface dialog, int id) {
    				//mPreferences = getSharedPreferences(AWESOME_NAME, MODE_PRIVATE);
    				removeDialog(Pager.DIALOG_WEB_SUCCESS);
    				dialog.cancel();
    				//removeDialog(Highscores.DIALOG_PREFERENCES);
    			}
    		});
    		alert = builder.create();
    		dialog = (Dialog) alert;
    		break;

    		////////////////////////////////////
    		
    		default:
    			dialog = null;
    	}
    	
    	return dialog;
    }
    
    
    @Override
    public void onBackPressed() {
        if (mPager.getCurrentItem() == 0) {
            // If the user is currently looking at the first step, allow the system to handle the
            // Back button. This calls finish() on this activity and pops the back stack.
            super.onBackPressed();
        } else {
            // Otherwise, select the previous step.
            mPager.setCurrentItem(mPager.getCurrentItem() - 1);
        }
    }

    /**
     * A simple pager adapter 
     * 
     */
    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
        	Fragment item = null;
        	
        	switch (position) {
        	case Pager.HOWTO :
        		item = new FragmentHowto();
        		break;
        	case Pager.PLAYERS :
        		item = new FragmentPlayers(mHighScores);
        		break;
        	case Pager.HIGHSCORES :
        		item = new FragmentHighscores();
        		break;
        	default:
        		item = new FragmentHowto();
        	}
        	//mPreferences = getSharedPreferences(Pager.AWESOME_NAME, MODE_PRIVATE);
//        	mPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//        	SharedPreferences.Editor edit = mPreferences.edit();
//        	edit.putInt(Pager.SAVED_FRAGMENT_NUM, position);
//        	edit.commit();
        	
            return item;
        }

        @Override
        public int getCount() {
            return NUM_PAGES;
        }
    }
}
